package com.yibo.interceptor;

import com.yibo.redis.RedisCommand;
import com.yibo.support.context.SpringContext;
import com.yibo.support.helper.Assert;
import com.yibo.support.helper.JsonHelper;
import com.yibo.support.helper.ObjectHelper;
import com.yibo.support.jwt.JWTUtils;
import com.yibo.support.pojo.Result;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

import static com.yibo.support.constant.ApiUrlConstant.PUBLIC_URL;
import static com.yibo.support.constant.YBConstant.*;

/**
 * 权限认证filter
 *
 * @author zhanglei
 */
public class HttpBasicAuthorizeFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
//        ServletContext context = filterConfig.getServletContext();
//        ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        //接口地址
        String path = req.getServletPath();

        //是公开的
        if(path.contains(PUBLIC_URL)){
            chain.doFilter(request,response);
            return ;
        }

        //如果是系统内部调用，直接放权
        String auth = req.getHeader(AUTH);
        if(auth != null){
            JWTUtils.JWTResult ret = JWTUtils.getInstance().checkToken(auth);
            Assert.isTrue(ret.getMsg(),!ret.isStatus());
            chain.doFilter(request,response);
            return ;
        }

        String token = req.getHeader("token");
        //先校验token是否正确
        JWTUtils.JWTResult result = JWTUtils.getInstance().checkToken(token);
        if(!result.isStatus()){
            response.getWriter().write(JsonHelper.toJson(new Result<>(-1,result.getMsg(),null)));
            return;
        }

        //再校验token是否过期
        String ip = req.getHeader(CLI_IP)+"";
        RedisCommand redisCommand = SpringContext.getBean(RedisCommand.class);
        Object ipUser = redisCommand.get(YIBO_USER_REDIS_PREFIX_IP+ip);
        Object tokenUser = redisCommand.get(YIBO_USER_REDIS_PREFIX_TOKEN+token);
        if(ObjectHelper.hasEmpty(ipUser,tokenUser)){
            redisCommand.remove(ip);
            redisCommand.remove(token);
            response.getWriter().write(JsonHelper.toJson(new Result(-120,"请先登录",null)));
        }

        chain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}
